package sp.service;

import sp.dao.BaseDao;
import sp.dao.NovelDao;
import sp.dao.NovelDaoImpl;
import sp.dao.Page;
import sp.entity.Novel;
import sp.service.NovelService;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NovelServiceImpl implements NovelService {
    NovelDao novelDao = new NovelDaoImpl();
    @Override
    public Page<Novel> findPage(String classId, String name, String author, int page, int rows) {
        Map<String,String> params = new HashMap<>();
        if(classId !=null&&classId.trim().length()>0) params.put("classId",classId);
        if(name !=null&&name.trim().length()>0) params.put("name",name);
        if(author !=null&&author.trim().length()>0) params.put("author",author);
        return novelDao.find(params,page,rows);

    }

    @Override
    public void delete(String id) {
        boolean autocommit = false;
        try {
            autocommit = BaseDao.begin();
            novelDao.delete(id);
            BaseDao.commit(autocommit);
        } catch (SQLException e) {
            try {
                BaseDao.rollback(autocommit);
            } catch (SQLException ex) {
                ex.printStackTrace();
                throw  new RuntimeException(ex);
            }
        }
    }

    @Override
    public void addNovel(Novel novel) {
        boolean autoCommit = false;
        try {
            autoCommit = BaseDao.begin();
            novelDao.addNovel(novel);
            BaseDao.commit(autoCommit);
        } catch (SQLException e) {
            try {
                BaseDao.rollback(autoCommit);
            } catch (SQLException e1) {
                e.printStackTrace();
                throw new RuntimeException(e1);
            }
        }
    }

    @Override
    public void updateNovel(Novel novel) {
        boolean autoCommit = false;
        try {
            autoCommit = BaseDao.begin();
            novelDao.updateNovel(novel);
            BaseDao.commit(autoCommit);
        } catch (SQLException e) {
            try {
                BaseDao.rollback(autoCommit);
            } catch (SQLException e1) {
                e.printStackTrace();
                throw new RuntimeException(e1);
            }
        }
    }

    @Override
    public List<Novel> findAll() {
        return novelDao.findAll();
    }
}
